# coding: utf-8

from flask_restful import Resource, Api
from flask import current_app, request

from app.api.codes import PARAMS_ILLEGAL
from app.api_v2.constant import CURRENT_APP_VERSION_KEY
from app.api_v2.version_schemas import version_schema
from app.api_v2.views import Response
from app.op.models import UserInfo
from app.token import AuthToken

api = Api()


@api.resource('/app/android/versions')
class AndroidVersionResource(Resource):

    app_type = 'android'

    def get(self):
        """
        获取App版本号及下载地址
        :return:
        """
        # 记录用户最后打开app时的版本
        app_login_version = request.args.get('app_version', '')
        if app_login_version:
            token = request.headers.get('token')
            # 如果是工程商登录, 则参与状态改为该工程商对此项目的参与状态
            user = AuthToken.verify_app_token(token) if token else None
            if user:
                user_info = UserInfo.default_user_info(user.id)
                user_info.app_login_version = app_login_version

        version = current_app.redis.hgetall(
            CURRENT_APP_VERSION_KEY % self.app_type
        ) or dict()

        return Response(
            body=dict(
                version=version.get('version'),
                url=version.get('url')
            )
        )

    def put(self):
        """
        更新版本号及下载地址
        :return:
        """
        data, errors = version_schema.load(request.get_json())
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )
        current_app.redis.hmset(CURRENT_APP_VERSION_KEY % self.app_type, data)
        return Response()


@api.resource('/app/ios/versions')
class IosVersionResource(AndroidVersionResource):
    """
    create by ld_wu 2017-11-29
    ios版本管理
    """
    app_type = 'ios'
